import { toast, promptBox, print, output } from 'nc-lightapp-front';
import moment from 'moment';
import { debug } from 'util';
let openFormData = null;
export default class Main {
	constructor(comp) {
		this.comp = comp;
	}

	// 新增页面头部按钮点击处理
	addHeaderClick = (btnCode) => {
		const { action, props } = this.comp;
		const { form } = props;
		return (props, bCode) => {
			//console.log(bCode);
			let selectedRows = [
				{
					...form.getAllFormValue('card').rows[0]
				}
			];
			// 新增页面编辑按钮
			if (btnCode === 'editA') {
				action.entryAct.editOnes(selectedRows);
			} else if (btnCode === 'unentry_status') {
				if (bCode === 'save') {
					action.entryAct.saveOnes(selectedRows);
				} else if (bCode === 'handentry') {
					action.entryAct.openEntryModal(selectedRows);
				} else if (bCode === 'qryentry') {
					action.qryEntryAct.qryEntry(selectedRows);
				} else if (bCode === 'psninfo') {
					action.psnAct.qryPsnInfo(selectedRows);
				} else if (bCode === 'printbill') {
					this.printBill(selectedRows);
				} else if (bCode === 'printpsninf') {
					this.printPsninf(selectedRows);
				}
			}
		};
	};

	getTableHeight = () => {
		const { props } = this.comp;
		const { emp } = props;
		const mainTable = document.getElementsByClassName('material-table');
		let tableHeight = 0;
		if (mainTable[0]) {
			// if (emp.addPageStatus == 'edit') {
			//     console.log('height', mainTable[0].clientHeight)
			//     tableHeight = mainTable[0].clientHeight - 300
			// }
			// else {
			//     tableHeight = mainTable[0].clientHeight - 36
			// }
			tableHeight = 300;
		}
		return tableHeight;
	};

	//是否确认返回
	beSureBack = () => {
		const { props } = this.comp;
		const { dispatch, button, emp } = props;
		let language = emp.language;
		if (emp.isUnentryEdit) {
			promptBox({
				color: 'info',
				title: emp.language['gx6008-000082'], //返回
				content: emp.language['gx6008-000074'], //是否确认返回
				beSureBtnName: emp.language['gx6008-000092'], // 是
				cancelBtnName: emp.language['gx6008-000093'], // 否
				hasCloseBtn: true, // 是否有关闭
				beSureBtnClick: this.goToBackMainPage
			});
		} else {
			this.goToBackMainPage();
		}
	};

	// 返回按钮返回主页面表格
	goToBackMainPage = () => {
		const { props } = this.comp;
		const { dispatch, button, emp, form } = props;
		const contractnum = form.getFormItemsValue('hi_psndoc_ctrt', 'contractnum').value;
        const isDisabled = form.getFormItemsDisabled('hi_psndoc_ctrt', 'contractnum');
		let callback = () => {
            dispatch({
                type: 'emp/update',
                payload: {
                    page: 'main'
                }
            });
            if(emp.widget){
                button.setButtonVisible({
                    refresh: false,
                    handentry: false,
                    save: false,
                    qryentry: false,
                    psninfo: false,
                    query: false,
                    print: false
                });
                this.pubSub.publish('getWidgetTableData')
            }else{
                button.setButtonVisible({
                    save: false,
                    query: true
                });
                this.pubSub.publish('getMainTableData');
                this.comp.action.btnAct.initPageButton();
            }
        }

		if(isDisabled && contractnum){
            let postData = {
                codeList: [contractnum],
                pk_org: emp.orgValue.refpk
            }
            dispatch({
                type: 'emp/codeRollBack',
                payload: {
                    postData: postData
                }
            }).then((res) => {
                if(res.success) {
                    callback()
                }
            })
        }else{
            callback()
        }
	};

	// 开关表单
	closeForm = () => {
		const { props, action } = this.comp;
		const { emp, dispatch, form } = props;
		dispatch({
			type: 'emp/update',
			payload: {
				ctrtBtnDisp: 'none',
				ctrtOpenBtnDisp: 'inline',
				ctrtDisp: 'none'
			}
		});
	};

	// 开关表单
	openForm = () => {
		const { props } = this.comp;
		const { emp, dispatch, form } = props;
		dispatch({
			type: 'emp/update',
			payload: {
				ctrtBtnDisp: 'inline',
				ctrtOpenBtnDisp: 'none',
				ctrtDisp: 'inline'
			}
		});
		//this.formAfterEdit();
	};

	// 表格编辑后
	tableAfterEdit = async (platFormProps, moduleId, key, valuea, changedrows, index, record) => {
		// console.log('aaaaaa', index, key);
		const { props } = this.comp;
		const { emp, dispatch, editTable } = props;
		//console.log('5',key, valuea, index, record)
		//console.log('1',editTable.getAllRows('material'))//true
		//let tableData = editTable.getAllRows('material');
		// let date = new Date();
		// let dateStr = date.toLocaleDateString();
		let nowYear = new Date().getFullYear().toString();
		let nowMonth = (new Date().getMonth() + 1).toString();
		let nowDay = new Date().getDate().toString();
		function timeAdd0(str) {
			if (str.length <= 1) {
				str = '0' + str;
			}
			return str;
		}
		nowYear = timeAdd0(nowYear);
		nowMonth = timeAdd0(nowMonth);
		nowDay = timeAdd0(nowDay);
		let dateString = nowYear + '-' + nowMonth + '-' + nowDay;
		// dateStr = dateStr.replace("/", "-0").replace("/", "-");
		// console.log('12',dateStr)
		//是否接收和缺件互斥
		if (key === 'uncommit') {
			if (valuea) {
				editTable.setValByKeyAndIndex('material', index, 'isreceive', { value: false });
				editTable.setValByKeyAndIndex('material', index, 'receivedate', {
					value: null,
					display: undefined,
					scale: '0'
				});
			}
		}
		if (key === 'isreceive') {
			if (valuea) {
				editTable.setValByKeyAndIndex('material', index, 'receivedate', {
					value: dateString,
					display: dateString,
					scale: '0'
				});
				editTable.setValByKeyAndIndex('material', index, 'uncommit', { value: false });
			} else {
				editTable.setValByKeyAndIndex('material', index, 'receivedate', {
					value: null,
					display: undefined,
					scale: '0'
				});
			}
		}
	};

	// 表单编辑后
	formAfterEdit = async (platFormProps, formId, key, value, preVal) => {
		const { props } = this.comp;
		const { emp, dispatch, form, meta } = props;
		// console.log('tableafteredit');
		let formData = form.getAllFormValue('hi_psndoc_ctrt');
		// console.log('formData', formData);
		let postData = {
			key,
			model: formData,
			pk_org: emp.orgValue.refpk
		};

		try {
			let res = await dispatch({
				type: 'emp/formEditAfter',
				payload: {
					postData: postData
				}
			});

			if (res.success && this.checkErrorMsg(res)) {
				//console.log('res', res)
				// if(!!res.data.disableItem){
				//     Object.keys(res.data.disableItem).forEach(function(key){
				//         form.setFormItemsDisabled('hi_psndoc_ctrt',{[key]:res.data.disableItem[key]});
				//         //console.log('66666',key,res.data.disableItem[key]);
				//     });
				//     //form.setFormItemsDisabled('hi_psndoc_ctrt',{'pk_jobgrade':res.data.disableItem.pk_jobgrade});
				// }
				let template = meta.getMeta();
				template['hi_psndoc_ctrt'] = res.data.formMeta;
				meta.setMeta(template);
				// form.setFormItemsDisabled('hi_psndoc_ctrt', {
				//     //code: !res.data.formMeta.items[i].disabled
				//     'contractnum': true
				// });
				//debugger
				for (let i = 0; i < res.data.formMeta.items.length; i++) {
					let code = res.data.formMeta.items[i].attrcode;
					form.setFormItemsDisabled('hi_psndoc_ctrt', {
						[code]: res.data.formMeta.items[i].disabled
					});
				}
				form.setAllFormValue({
					hi_psndoc_ctrt: res.data.formData.hi_psndoc_ctrt
				});
				//console.log('yilaile')
				//console.log(form.getAllFormValue('hi_psndoc_ctrt'))
			}
		} catch (e) {}
	};

	// 检查返回值里是否有 errorMsg
	checkErrorMsg = (res) => {
		if (res && res.data && (res.data.errMsg || res.data.message)) {
			toast({
				color: 'danger',
				content: res.data.errMsg || res.data.message
			});
		}
		return true;
	};

	// 打印
	printBill = (selectedRows) => {
		print('pdf', '/nccloud/hrtrn/entrymng/EntryPrintAction.do', {
			appcode: '60092010',
			nodekey: '60081010',
			oids: [ selectedRows[0].values['pk_entryapply'].value ]
		});
	};

	printPsninf = (selectedRows) => {
		print('pdf', '/nccloud/hrtrn/entrymng/EntryPrintPsninfoAction.do', {
			appcode: '60092020',
			nodekey: '60092020',
			oids: [ selectedRows[0].values['pk_psnjob'].value ]
		});
	};

	// 初始化
	didMount = () => {
		//监听鼠标离开input元素时触发失焦事件
		/*if (this.addPage) {
			// console.log('...', this.addPage);
			this.addPage.addEventListener('mouseover', () => {
				let inputs = this.addPage.getElementsByTagName('input');
				Array.prototype.map.call(inputs, function(item) {
					item.blur();
				});
			});
		}*/
	};
}
